<template>
  <div>
    <el-dialog :title="title" :visible.sync="dialogVisible" width="70%" :close-on-click-modal="false" :before-close="close">
      <el-form ref="RefForm" :model="formData" label-width="110px" :validate-on-rule-change="false" :rules="formRules" status-icon>
        <el-form-item label="用户名" prop="showName">
          <el-input v-model="formData.showName" maxlength="16" show-word-limit />
        </el-form-item>
        <el-form-item label="登陆账号" prop="loginName">
          <el-input v-model="formData.loginName" auto-complete="new-password" maxlength="16" show-word-limit />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="formData.password" auto-complete="new-password" show-password maxlength="16" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="formData.confirmPassword" auto-complete="new-password" show-password maxlength="16" />
        </el-form-item>
        <el-form-item label="所属组织架构" prop="checkedRole">
          <div style="margin: 15px 0"></div>
          <el-tree
            ref="tree"
            node-key="id"
            highlight-current
            class="filter-tree"
            :data="roleList"
            :default-checked-keys="editedRole"
            :default-expanded-keys="editedRole"
            :props="defaultProps"
            show-checkbox
            @check-change="handleCheckChange"
          />
        </el-form-item>
        <el-form-item label="是否为管理员">
          <el-switch v-model="isAdmin" active-text="是" inactive-text="否" active-color="#13ce66" inactive-color="#ff4949" />
        </el-form-item>
        <!-- <el-form-item label="状态">
				<el-radio v-model="formData.isEnable" :label="false">启用</el-radio>
				<el-radio v-model="formData.isEnable" :label="true">禁用</el-radio>
        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="loadingSubmit" type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { RoleSearch } from '@/api/Role'
import { HostUser, HostUserDetail } from '@/api/HostUser'
import { eleValidator } from '@/utils/tools'
export default {
  data() {
    return {
      // 树形结构显示的值
      defaultProps: {
        children: 'children',
        label: 'roleName'
      },
      id: '',
      // 编辑模式
      isEdit: false,
      isAdmin: false,
      title: '',
      loadingSubmit: false,
      isCheck: false,
      dialogVisible: false,
      formData: {
        showName: '',
        loginName: '',
        password: '',
        checkedRole: '', // 单选 公司roleId
        selectRoles: [], // 多选，选择的公司
        confirmPassword: '',
        isAdmin: false
      },

      editedRole: [],
      editDepartments: [],
      roleList: [],
      formRules: {
        showName: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          {
            validator: eleValidator([{ rule: 'isEmpty', msg: '名称不能为空' }]),
            trigger: 'blur'
          }
        ],
        checkedRole: {
          required: true,
          message: '请选择所属公司',
          trigger: 'blur'
        },
        loginName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            validator: eleValidator([
              { rule: 'isEmpty', msg: '用户名不能为空' },
              {
                rule: 'isRepeat',
                msg: {
                  value: '用户名重复，用户名必须全系统唯一，请更换',
                  url: '/HostUser/Exists',
                  key: 'loginName'
                }
              },
              { rule: 'isNumberLetterLine', msg: '只能输入数字字母下划线' }
            ]),
            trigger: 'blur'
          }
        ],
        password: [],
        confirmPassword: [],
        password_back: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            validator: eleValidator([
              {
                rule: 'isPassword',
                msg: '最少输入位数10；必须包含数字字母和特殊字符；不可输入汉字或3位连续数字或3位相同数字'
              }
            ]),
            trigger: 'blur'
          }
        ],
        confirmPassword_back: [
          { required: true, message: '请输入确认密码', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('确认密码不能为空'))
              } else if (value === this.formData.password) {
                callback()
              } else {
                if (this.formData.password) {
                  callback(new Error('密码不一致'))
                } else {
                  callback(new Error('请输入密码再输入确认密码'))
                }
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {
    'formData.password': {
      deep: true,
      handler: function (newValue, oldValue) {
        if (this.isEdit === true) {
          // 编辑模式
          if (newValue !== '') {
            this.formRules.password = this.formRules.password_back
            this.formRules.confirmPassword = this.formRules.confirmPassword_back
          } else {
            this.formRules.password = {}
            this.formRules.confirmPassword = {}
          }
        } else {
          // 添加模式
          this.isEdit = false
          this.isCheck = false
        }
      }
    }
  },
  mounted: function () {},
  methods: {
    handleCheckChange(data, checked) {
      if (checked) {
        this.formData.checkedRole = data.id
        this.$refs.tree.setCheckedKeys([data.id], true)
      } else {
        // this.checkedRole = ''
      }
      console.info('handleCheckChange', data, checked, this.checkedRole)
    },
    async getRole(query) {
      const obj = query || {
        pageIndex: 1,
        pageSize: 10
      }

      if (obj.search === undefined) {
        obj.search = []
      }
      obj.search.push({
        key: 'parentId',
        value: 0,
        operation: 0
      })

      try {
        const {
          data: { items }
        } = await RoleSearch(obj)
        this.roleList = items
      } catch (err) {
        console.log(err)
      }
    },

    open(row) {
      this.dialogVisible = true
      this.$nextTick(function () {
        this.$refs.RefForm.clearValidate()
        this.editedRole = []
      })
      // 查询用户信息
      if (row) {
        var id = row.id
        this.title = '编辑用户'
        this.formRules.password = {}
        this.formRules.confirmPassword = {}
        this.isEdit = true
        this.isCheck = true

        HostUserDetail({ id }).then((res) => {
          this.editedRole = []
          this.id = res.data.id
          this.formData.loginName = res.data.loginName
          this.formData.showName = res.data.showName
          this.isAdmin = res.data.isAdmin
          this.formData.password = this.formData.confirmPassword = ''
          this.formData.checkedRole = res.data.roleId
          if (res.data.departments.length > 0) {
            this.editedRole = res.data.departments.map((r) => r.departId)
            this.editDepartments = res.data.departments
          }
        })
      } else {
        this.isEdit = false
        this.isCheck = false
        this.formRules.password = this.formRules.password_back
        this.formRules.confirmPassword = this.formRules.confirmPassword_back
        this.title = '新增用户'
      }
    },
    // 提交
    handleSubmit() {
      this.loadingSubmit = true
      this.$refs.RefForm.validate(async (valid) => {
        if (valid) {
          var selectIds = this.$refs.tree.getCheckedKeys()
          if (selectIds.length <= 0) {
            this.$message.warning('请选择一个公司')
            this.loadingSubmit = false
          } else {
            let method = ''
            let obj = {}
            if (this.isEdit) {
              method = 'PUT'
              obj = {
                id: this.id,
                loginName: this.formData.loginName,
                showName: this.formData.showName,
                password: this.formData.password,
                isAdmin: this.isAdmin,
                roleId: this.formData.checkedRole
              }
            } else {
              method = 'POST'
              obj = {
                loginName: this.formData.loginName,
                showName: this.formData.showName,
                password: this.formData.password,
                isAdmin: this.isAdmin,
                roleId: this.formData.checkedRole
              }
            }
            obj.departments = selectIds.map((r) => {
              return { departId: r }
            })

            console.info(obj)
            const res = await HostUser(method, obj)
            this.loadingSubmit = false
            if (res.code >= 200 || res.code < 300) {
              if (this.isEdit) {
                this.$message.success('操作成功，修改待下次登录后生效')
              } else {
                this.$message.success('操作成功')
              }
              // MessageBox.confirm('操作成功，重新登陆后权限生效', '确认注销', {
              //   confirmButtonText: '重新登陆',
              //   cancelButtonText: '取消',
              //   type: 'warning'
              // }).then(async () => {
              //   await this.$store.dispatch('user/logout')
              //   this.$router.push(`/login?redirect=${this.$route.fullPath}`)
              // })
              this.cancel()
              this.$emit('getList')
            } else {
              this.$message.error('操作失败！')
            }
          }
        } else {
          this.loadingSubmit = false
        }
      })
    },
    // 单选
    handlecheckedRoleChange() {},
    async close() {
      this.dialogVisible = false
      this.formData.showName = ''
      this.formData.loginName = ''
      this.formData.password = ''
      this.formData.confirmPassword = ''
      this.formData.checkedRole = ''
      this.formData.isAdmin = false
      this.isAdmin = false
      this.editedRole = []
      this.editDepartments = []
      // 设置编辑模式
      await this.$store.dispatch('user/setEdit', { status: false, id: null })
    },
    cancel() {
      this.close()
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
